package mqtt

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"gitee.com/injoyai/goutil/crypt/tls"
	"time"
)

func WithAliyun(cfg *ConfigWithAliyun) (o *Config, topicPrefix string) {
	clientID := cfg.GroupID + "@@@" + cfg.ClientID
	return &Config{
		BrokerURL: cfg.BrokerURL,
		ClientID:  clientID,
		Qos:       cfg.Qos,
		Retained:  cfg.Retained,
		Username:  "Signature|" + cfg.AccessKey + "|" + cfg.InstanceID,
		Password:  cfg.HMACSHA1(clientID),
		Timeout:   cfg.Timeout,
		Debug:     cfg.Debug,
	}, cfg.Topic + "/p2p/" + cfg.GroupID + "@@@"
}

// ConfigWithAliyun 选项
type ConfigWithAliyun struct {
	InstanceID string        //可选
	BrokerURL  string        //必选
	AccessKey  string        //可选
	SecretKey  string        //可选
	Topic      string        //可选,阿里云(必选),其他类型无效
	ClientID   string        //必选,本机Topic地址
	GroupID    string        //必选
	Qos        byte          //可选
	Retained   bool          //可选
	Timeout    time.Duration //必选,超时时间
	Debug      bool          //可选,调试模式,打印日志
	KeepAlive  time.Duration //心跳时间
}

func (this *ConfigWithAliyun) HMACSHA1(dataToSign string) string {
	mac := hmac.New(sha1.New, []byte(this.SecretKey))
	mac.Write([]byte(dataToSign))
	result := mac.Sum(nil)
	return base64.StdEncoding.EncodeToString(result)
}

// Config 配置
type Config struct {
	BrokerURL string        //必选,不要忘记 tcp://
	ClientID  string        //必选,服务器Topic地址
	Qos       byte          //可选
	Retained  bool          //可选
	Username  string        //用户名
	Password  string        //密码
	Timeout   time.Duration //超时时间
	Debug     bool          //调试模式,打印日志
	KeepAlive time.Duration //心跳时间

	TLS       bool
	TLSConfig tls.Config
}
